# 沂南四中高子杰
import math
import tkinter as tk
from tkinter import ttk, messagebox
from sympy import symbols, Eq, solve, sympify
from sympy.parsing.sympy_parser import parse_expr


class CalculatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("综合科学计算器 沂南四中 六·13 高子杰")
        self.root.geometry("600x400")

        # main
        self.notebook = ttk.Notebook(root)
        self.tab_basic = ttk.Frame(self.notebook)
        self.tab_scientific = ttk.Frame(self.notebook)

        self.notebook.add(self.tab_basic, text="普通计算")
        self.notebook.add(self.tab_scientific, text="科学计算")
        self.notebook.pack(expand=True, fill="both")

        # init
        self.create_basic_tab()
        self.create_scientific_tab()

        # history
        self.history = []

    def create_basic_tab(self):
        """普通计算界面"""
        frame = ttk.Frame(self.tab_basic)
        frame.pack(padx=10, pady=10, fill="both", expand=True)

        # entry text
        self.basic_entry = ttk.Entry(frame, font=('Arial', 14))
        self.basic_entry.grid(row=0, column=0, columnspan=4, sticky="ew", pady=5)

        # btn
        buttons = [
            ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
            ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
            ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
            ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
            ('C', 5, 0), ('(', 5, 1), (')', 5, 2), ('^', 5, 3)
        ]

        for (text, row, col) in buttons:
            btn = ttk.Button(frame, text=text,
                             command=lambda t=text: self.on_button_click(t))
            btn.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)

        # wg
        for i in range(4):
            frame.columnconfigure(i, weight=1)
        for i in range(6):
            frame.rowconfigure(i, weight=1)

    def create_scientific_tab(self):
        """科学计算界面"""
        frame = ttk.Frame(self.tab_scientific)
        frame.pack(padx=10, pady=10, fill="both", expand=True)

        # se
        self.sci_entry = ttk.Entry(frame, font=('Arial', 14))
        self.sci_entry.grid(row=0, column=0, columnspan=5, sticky="ew", pady=5)

        # btns
        sci_buttons = [
            ('sin', 1, 0), ('cos', 1, 1), ('tan', 1, 2),
            ('√', 1, 3), ('π', 1, 4),
            ('log', 2, 0), ('log10', 2, 1), ('e', 2, 2),
            ('rad', 2, 3), ('^', 2, 4),
            ('(', 3, 0), (')', 3, 1), ('C', 3, 2),
            ('=', 3, 3), ('⌫', 3, 4), ('7', 4, 0), ('8', 4, 1), ('9', 4, 2), ('/', 4, 3),
            ('4', 5, 0), ('5', 5, 1), ('6', 5, 2), ('*', 5, 3),
            ('1', 6, 0), ('2', 6, 1), ('3', 6, 2), ('-', 6, 3),
            ('0', 7, 0), ('.', 7, 1), ('+', 7, 2), ('/', 7, 3),
        ]

        for (text, row, col) in sci_buttons:
            btn = ttk.Button(frame, text=text,
                             command=lambda t=text: self.on_sci_button_click(t))
            btn.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)

        # wg
        for i in range(5):
            frame.columnconfigure(i, weight=1)
        for i in range(4):
            frame.rowconfigure(i, weight=1)

    def on_button_click(self, char):
        """处理普通计算器按钮点击"""
        current = self.basic_entry.get()
        if char == '=':
            try:
                result = eval(current)
                self.basic_entry.delete(0, tk.END)
                self.basic_entry.insert(0, str(result))
                self.history.append(f"{current} = {result}")
            except Exception as e:
                messagebox.showerror("错误", f"计算错误：{e}")
        elif char == 'C':
            self.basic_entry.delete(0, tk.END)
        elif char == '^':
            self.basic_entry.insert(tk.END, '**')
        else:
            self.basic_entry.insert(tk.END, char)

    def on_sci_button_click(self, char):
        """处理科学计算器按钮点击"""
        current = self.sci_entry.get()
        special_map = {
            '√': 'sqrt(', 'π': 'math.pi', 'e': 'math.e',
            'rad': 'math.radians(', 'sin': 'math.sin(',
            'cos': 'math.cos(', 'tan': 'math.tan(',
            'log': 'math.log(', 'log10': 'math.log10(',
            '⌫': ''
        }

        if char == '=':
            try:
                expr = current.replace('^', '**')
                result = eval(expr, {'math': math})
                self.sci_entry.delete(0, tk.END)
                self.sci_entry.insert(0, str(result))
                self.history.append(f"{expr} = {result}")
            except Exception as e:
                messagebox.showerror("错误", f"计算错误：{e}")
        elif char == 'C':
            self.sci_entry.delete(0, tk.END)
        elif char == '⌫':
            self.sci_entry.delete(len(current) - 1, tk.END)
        elif char in special_map:
            self.sci_entry.insert(tk.END, special_map[char])
        else:
            self.sci_entry.insert(tk.END, char)


if __name__ == '__main__':
    tki = tk.Tk()
    app = CalculatorApp(tki)
    tki.mainloop()
